#include "widget.h"
#include "ui_widget.h"
// #include <sstream>


WINBOOL runAndWait(const QString cmdLine, bool hideWindow = false) {
    STARTUPINFOA si = {};
    PROCESS_INFORMATION pi = {};
    si.cb = sizeof(si);

    if (hideWindow) {
        si.dwFlags = STARTF_USESHOWWINDOW;
        si.wShowWindow = SW_HIDE;
    }

    auto res = CreateProcessA(NULL, (LPSTR)cmdLine.toLocal8Bit().constData(), NULL, NULL, FALSE, 0, NULL, NULL,
                   &si, &pi);
    if (res){
        WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
    else
        return false;

    return true;
}

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->m_btn_print->setEnabled(false);
    ui->m_btn_merge->setEnabled(false);
    ui->m_btn_delete->setEnabled(false);
    ui->m_btn_clean->setEnabled(false);


    //添加打印机
    QStringList printList = QPrinterInfo::availablePrinterNames();

    //开启拖放
    setAcceptDrops(true);

    //初始化
    m_model = new QStandardItemModel(this);
    m_model->setHorizontalHeaderLabels({"文件名称","文件大小","文件路径"});



    ui->m_lv_main->setModel(m_model);


    //信号和槽
    this->connect(m_model,&QStandardItemModel::rowsInserted,[=](){

        // ui->m_btn_print->setEnabled(m_model->rowCount());
         ui->m_btn_merge->setEnabled(m_model->rowCount());
         ui->m_btn_clean->setEnabled(m_model->rowCount());

    });


    this->connect(m_model,&QStandardItemModel::rowsRemoved,[=](){

        // ui->m_btn_print->setEnabled(m_model->rowCount());
        ui->m_btn_merge->setEnabled(m_model->rowCount());

    });


    this->connect(ui->m_lv_main,&YTableView::currentModelChanged,[=](){

        ui->m_btn_clean->setEnabled(this->m_model->rowCount());
        ui->m_btn_delete->setEnabled(ui->m_lv_main->currentIndex().isValid());

    });


}

Widget::~Widget()
{
    delete ui;
}


void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    // 检查拖拽的内容是否包含文件
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
        qDebug() << event->mimeData()->urls();
    }

}

QString Widget::getTempFileName() {
    QString tempPath = QDir::tempPath();
    QString uniqueName = QUuid::createUuid().toString(QUuid::WithoutBraces);
    QString tempFileName = tempPath + "/" + uniqueName + ".tmp";
    return tempFileName;
}

void Widget::addFieListToModel(QStringList fl)
{

    foreach (auto &filePath, fl) {

        //查找是否已经添加了
        bool isNotExsits = m_model->findItems(filePath,Qt::MatchExactly,2).count()==0;
        bool isPdfFile = QFileInfo(filePath).isFile() && QFileInfo(filePath).suffix().endsWith("pdf");
        QStandardItem *itemPath = new QStandardItem(filePath);
        // qDebug() <<( QFileInfo(item.toLocalFile()).suffix() == ".pdf");
        if (ui->obj_checkbox_repeat->isChecked()){
            isNotExsits = true;
        }
        if (isNotExsits && isPdfFile){

            QStandardItem *itemName = new QStandardItem(QFileInfo(filePath).fileName());
            itemName->setIcon(QIcon(":/app.ico"));
            QStandardItem *itemSize = new QStandardItem( QObject::tr("%1字节").arg(QFileInfo(filePath).size()));

            QList<QStandardItem*> row ;
            row << itemName << itemSize  << itemPath;
            m_model->appendRow(row);
        }

    }
}

QString Widget::mergePdf()
{




   // 获取要打印的文件路径列表
     QStringList pdfList;
     for(int i=0;i<m_model->rowCount();i++){
         pdfList << QObject::tr("\"%1\"").arg(m_model->item(i,2)->text());
     }
     auto tmp_file_name = getTempFileName();

    //制作命令行
    QString cmd_line = QObject::tr("pdftk.exe %1 cat output \"%2\"").arg(pdfList.join(" "),tmp_file_name);
     QProcess::execute(cmd_line,{});

    return tmp_file_name;





}


void Widget::dropEvent(QDropEvent *event)
{

    const QMimeData *mimeData = event->mimeData();
    QStringList fileList;
    if (mimeData->hasUrls()) {
        foreach (auto &item, mimeData->urls()) {
            fileList << item.toLocalFile();
    }

        addFieListToModel(fileList);

}
}


void Widget::on_m_btn_print_clicked()
{


}


void Widget::on_m_btn_clean_clicked()
{

    m_model->removeRows(0,m_model->rowCount());
    ui->m_btn_clean->setEnabled(false);

}


void Widget::on_m_btn_merge_clicked()
{

    auto tmp_file_name = mergePdf();
    QString cmd_line = QObject::tr("C:\\Program Files (x86)\\Adobe\\Reader 9.0\\Reader\\AcroRd32.exe \"%1\"").arg(tmp_file_name);
    QProcess::execute(cmd_line,{});
}




void Widget::on_m_btn_add_clicked()
{
    auto fileList = QFileDialog::getOpenFileNames(this,"选择pdf文件档","","*.pdf");
    addFieListToModel(fileList);
}


void Widget::on_m_btn_delete_clicked()
{
    auto mi = ui->m_lv_main->currentIndex();
    if (!mi.isValid())
        return ;
    m_model->removeRows(mi.row(),1);
     ui->m_btn_clean->setEnabled(this->m_model->rowCount());
}

